import Layoutview from '@/views/layout.vue'
import { createRouter, createWebHistory } from 'vue-router'
// 导入 pinia 数据
import { useUserStore } from '@/stores/user'
// 引入进度条 
import NProgress from 'nprogress'
import { refreshToken } from '@/api/userApi'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // // 主页 页面
    {
      path: '/',
      name: 'layout',
      component: Layoutview
    },
    // 登录页
    {
      path: '/login',
      name: 'login',
      meta: {
        nologin: true
      },
      component: () => import('@/views/login.vue')
    },
    // 注册页
    {
      path: '/register',
      name: 'register',
      meta: {
        nologin: true
      },
      component: () => import('@/views/register.vue')
    },
    // 404页面
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      meta: {
        nologin: true
      },
      component: () => import('@/views/404found.vue')
    }
  ],
})
// 导航守卫 前置
router.beforeEach(async (to, from, next) => {
  // 进度条开始执行
  NProgress.start()
  await refreshToken()
  const store = useUserStore()
  if (!store.accessToken && !to.meta.nologin) {
    NProgress.done()
    next({ name: 'login' })
    return;
  }
  next()
  NProgress.done()
})
// 导航守卫 后置
router.afterEach(() => {
  // 执行完毕删除进度条
  NProgress.remove()
})
export default router
